package org.jeecg.modules.third.digitalseal.utils;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.itextpdf.text.pdf.AcroFields;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.util.CheckBankCardIUtil;
import org.jeecg.common.util.DateUtils;
import org.jeecg.common.util.DictUtil;
import org.jeecg.modules.wlhy.company.entity.HyCompany;
import org.jeecg.modules.wlhy.company.service.IHyCompanyService;
import org.jeecg.modules.wlhy.customer.entity.HyCustomer;
import org.jeecg.modules.wlhy.customer.entity.HyCustomerCompany;
import org.jeecg.modules.wlhy.customer.service.IHyCustomerCompanyService;
import org.jeecg.modules.wlhy.customer.service.IHyCustomerService;
import org.jeecg.modules.wlhy.hycarrier.entity.HyCarrier;
import org.jeecg.modules.wlhy.hycarrier.service.IHyCarrierService;
import org.jeecg.modules.wlhy.hydriver.entity.HyDriver;
import org.jeecg.modules.wlhy.hydriver.service.IHyDriverService;
import org.jeecg.modules.wlhy.hydriverbank.entity.HyDriverBank;
import org.jeecg.modules.wlhy.hydriverbank.service.IHyDriverBankService;
import org.jeecg.modules.wlhy.hyvehicle.entity.HyVehicle;
import org.jeecg.modules.wlhy.hyvehicle.service.IHyVehicleService;
import org.jeecg.modules.wlhy.order.entity.HyOrder;
import org.jeecg.modules.wlhy.order.service.IHyOrderService;
import org.jeecg.modules.wlhy.setting.service.IHySettingService;
import org.jeecg.modules.wlhy.shipping.entity.HyShippingNote;
import org.jeecg.modules.wlhy.shipping.service.IHyShippingNoteService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import sun.misc.BASE64Encoder;

import java.io.*;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;

@Component
@Slf4j
public class GeneratePDF {

    public static String PATH_SUBFIX;//路径前缀
    public static String VEHICLE_TEMPLATE_PATH;//车辆挂靠声明模板
    public static String SHIPPING_TEMPLATE_PATH;//运输协议模板

    //文件保存地址路径
    public static String SAVE_CONTRACT_ADDR = "documents" + File.separator + DateUtils.getDate("yyyyMMdd") + File.separator;

    //PDF后缀
    public static String PDF_SUFFIX = ".pdf";
    //司机签名文件名前缀
    public static String SIGNET_NAME_SUBFIX = "司机签名_";
    //车辆挂靠声明文件名前缀
    public static String VEHICLE_NAME_SUBFIX = "车辆挂靠声明_";
    //运输协议文件名前缀
    public static String SHIPPING_NAME_SUBFIX = "运输协议_";


    @Autowired
    public IHySettingService hySettingService;

    @Value(value = "${jeecg.path.upload}")
    private String uploadpath;

    @Autowired
    private IHyCustomerCompanyService hyCustomerCompanyService;

    @Autowired
    private IHyCompanyService hyCompanyService;

    @Autowired
    private IHyCustomerService hyCustomerService;
    @Autowired
    private IHyOrderService hyOrderService;
    @Autowired
    private IHyDriverBankService driverBankService;

    @Autowired
    private IHyShippingNoteService hyShippingNoteService;

    @Autowired
    private IHyVehicleService hyVehicleService;

    @Autowired
    private IHyDriverService hyDriverService;

    @Autowired
    private DictUtil dictUtil;

    @Autowired
    private IHyCarrierService carrierService;

    //运输合同签署
    public Result pdfUtil(JSONObject order, HyShippingNote shippingNote, HyDriver driver) {

        if (order == null) {
            return Result.error("货源信息异常!");
        }
        HyCustomer customer = hyCustomerService.getById(order.get("customerId").toString());
        if (customer == null) {
            return Result.error("未查询到货主信息!");
        }
        //HyCustomerCompany customerCompany = hyCustomerCompanyService.getByCustomerId(order.get("customerId").toString());
        HyCustomerCompany customerCompany = hyCustomerCompanyService.getById(order.get("costServiceId").toString());
        if (customerCompany == null) {
            return Result.error("货主未绑定分公司");
        }
        HyCompany company = hyCompanyService.getById(customerCompany.getCompanyId());
        if (company == null) {
            return Result.error("分公司信息不存在");
        }
        if (StringUtils.isEmpty(company.getElectronicSeal())) {
            return Result.error("请配置分公司电子公章");
        }
        if (StringUtils.isEmpty(driver.getDriverAutograph())) {
            return Result.error("司机签名图片不存在");
        }

        HyVehicle hyVehicle = null;
        if (null != shippingNote) {
            hyVehicle = this.hyVehicleService.getById(shippingNote.getVehicleId());
        }

        String pathSubfix = uploadpath + File.separator;
        //模板路径
        String shippingTemplatePath = pathSubfix + hySettingService.getSettingValueByTag("driver_shipping_template");

        //输出路径
        String outputName2 = SAVE_CONTRACT_ADDR + SHIPPING_NAME_SUBFIX +
                DateUtils.getDate("yyyyMMddHHmmss") + "_" + System.currentTimeMillis() + PDF_SUFFIX;
        String outputName = pathSubfix + outputName2;

        File fileDir = new File(pathSubfix + SAVE_CONTRACT_ADDR);
        if (!fileDir.exists()) {
            fileDir.mkdirs();//创建目录
        }
        //甲方电子公章图片地址
        String jf_img = pathSubfix + company.getElectronicSeal();
        byte[] bytes = null;

        //乙方签名图片地址
        String yf_img = pathSubfix + driver.getDriverAutograph();
        byte[] yfbytes = null;

        OutputStream os = null;
        PdfStamper ps = null;
        PdfReader reader = null;

        log.info("开始生成PDF合同 {}, {}, {}, {}, {}", driver.getDriverName(), outputName2, pathSubfix + SAVE_CONTRACT_ADDR, jf_img, yf_img);
        try {
            FileInputStream fileInputStream3 = new FileInputStream(shippingTemplatePath);
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年MM月dd日");

            //图片的输入流
            FileInputStream fileInputStream = new FileInputStream(jf_img);
            bytes = new byte[fileInputStream.available()];
            fileInputStream.read(bytes);

            //图片的输入流2
            FileInputStream fileInputStream2 = new FileInputStream(yf_img);
            yfbytes = new byte[fileInputStream2.available()];
            fileInputStream2.read(yfbytes);

            //图片转码
            BASE64Encoder encoder = new BASE64Encoder();
            os = new FileOutputStream(new File(outputName));
            //读取pdf表单
            reader = new PdfReader(fileInputStream3);
            //根据表单生成一个新的pdf文件
            ps = new PdfStamper(reader, os);
            //获取pdf表单
            AcroFields form = ps.getAcroFields();
            //给表单中添加中文字体
            BaseFont bf = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
            form.addSubstitutionFont(bf);
            Map<String, Object> data = new HashMap<String, Object>();

            //合同编号
            if (StrUtil.isNotEmpty(order.getString("contractNum"))) {
                data.put("htbh", order.getString("contractNum"));
            }

            //甲方名称
            data.put("jf", company.getCompanyName());
            //乙方名称
            data.put("yf", driver.getDriverName());

            //甲方合同章
            data.put("jf_img", encoder.encode(bytes));
            //乙方签字章
            data.put("yf_img", encoder.encode(yfbytes));
            //货源号
            data.put("orderNum", order.getString("orderNum"));
            //货物名称
            data.put("descriptionOfGoods", order.getString("descriptionOfGoods"));

            //货物总重量
            if (order.getString("totalGoodsWeight") == null) {
                data.put("totalGoodsWeight", "--");
            } else {
                data.put("totalGoodsWeight", order.getString("totalGoodsWeight"));

            }
            //运费计算方式
            data.put("shippingType", order.getString("shippingType_dictText"));

            //亏损货物单价
            data.put("lossGoodsUnitPrice", order.getString("lossGoodsUnitPrice"));
            //免赔方式
            data.put("lossType", order.getString("lossType_dictText"));
            //免赔金额
            data.put("lossProportion",order.getString("lossProportion"));
            //发货地址
            data.put("sendAddressName", order.getString("sendAddressName"));
            //发货人
            data.put("sendContactName", order.getString("sendContactName"));
            //发货联系人电话
            data.put("sendContactTel", order.getString("sendContactTel"));

            //要求发货时间
            if (order.getString("sendDate") != null) {
                //发货时间
                data.put("sendDate", order.getString("sendDate"));
            } else {
                //发货时间
                data.put("sendDate", "--");
            }

            //收货地址
            data.put("receiveAddressName", order.getString("receiveAddressName"));
            //收货人
            data.put("receiveContactName", order.getString("receiveContactName"));
            //收货联系人电话
            data.put("receiveContactTel", order.getString("receiveContactTel"));
            if (order.getString("receiveDate") != null) {
                //收货时间
                data.put("receiveDate", order.getString("receiveDate"));
            } else {
                //收货时间
                data.put("receiveDate", "--");
            }

            //货物单价(系统暂无)
            data.put("goodsUnitPrice", "--");

            if (shippingNote != null) {
                data.put("shippingNoteNumber", shippingNote.getShippingNoteNumber());
                //装货时间
                if (ObjectUtil.isNotEmpty(shippingNote.getStatusDtLoading())) {
                    data.put("statusDtLoading", simpleDateFormat.format(shippingNote.getStatusDtLoading()));
                    //签订日期
                    data.put("date", simpleDateFormat.format(shippingNote.getStatusDtLoading()));
                }
                //收货时间
                if (ObjectUtil.isNotEmpty(shippingNote.getStatusDtUnloading())) {
                    data.put("statusDtUnloading", simpleDateFormat.format(shippingNote.getStatusDtUnloading()));
                }

                //运量
                if (ObjectUtil.isNotEmpty(shippingNote.getGoodsWeightLoading())) {
                    data.put("goodsWeightLoading", shippingNote.getGoodsWeightLoading());
                }
                //运费单价
                data.put("shippingUnitPrice",shippingNote.getShippingUnitPrice());
                //应付运费
                data.put("costPayShipping",shippingNote.getCostPayShipping());

            } else {
                //装货时间
                data.put("statusDtLoading", simpleDateFormat.format(new Date()));
                //运量
                data.put("goodsWeightLoading", "--");
                //签订日期
                data.put("date", simpleDateFormat.format(new Date()));

                //运费单价
                data.put("shippingUnitPrice", order.getString("shippingUnitPrice"));
            }

            //车辆信息
            if (null != hyVehicle) {
                log.info("签章添加车辆信息， {}", hyVehicle.getVehicleNumber());
                data.put("vehicleNumber", hyVehicle.getVehicleNumber());
                data.put("vehicleType", hyVehicle.getVehicleType());
                data.put("vehicleLong", hyVehicle.getVehicleLong());
                data.put("vehicleHeight", hyVehicle.getVehicleHeight());
                data.put("grossMass", hyVehicle.getGrossMass());
            }

            //司机信息
            data.put("idcard", driver.getIdcard());
            //司机姓名
            data.put("driverName", driver.getDriverName());
            //司机电话
            data.put("telephone", driver.getTelephone());
            List<HyDriverBank> driverBanks = driverBankService.getByDriverId(driver.getId());
            if(driverBanks.size()==0){
                //司机开户行
                data.put("bankType", "--");
                //司机银行卡
                data.put("bankNum", "--");
            }else{
                log.info("签章添加司机银行卡信息， {} {} {} ", driverBanks.get(0).getBankName(), driverBanks.get(0).getBankType(), driverBanks.get(0).getBankNum());
                //户名
                data.put("craccname", driverBanks.get(0).getBankName());
                //司机开户行
                data.put("bankCode_dictText", CheckBankCardIUtil.getBankNameByBankCode(driverBanks.get(0).getBankType()));
                //司机银行卡
                data.put("craccno", driverBanks.get(0).getBankNum());
            }
            //大写金额
            String DXshippingUnitPrice = digitCapital(Double.parseDouble(order.getString("shippingUnitPrice")));
            data.put("DXshippingUnitPrice", DXshippingUnitPrice);

            if (shippingNote.getPayType().equals("2")) {
                HyCarrier hyCarrier = carrierService.getById(shippingNote.getCarrierId());
                if (StringUtils.isEmpty(hyCarrier.getCarrierName())) {
                    data.put("carrierName", "--");
                }else {
                    data.put("carrierName", hyCarrier.getCarrierName());
                }
                if (StringUtils.isEmpty(hyCarrier.getIdcard())) {
                    data.put("carrierIdCard", "--");
                }else {
                    data.put("carrierIdCard", hyCarrier.getIdcard());
                }
                if (StringUtils.isEmpty(hyCarrier.getTel())) {
                    data.put("carrierTel", "--");
                }else {
                    data.put("carrierTel", hyCarrier.getTel());
                }
                if (StringUtils.isEmpty(hyCarrier.getBankNum())) {
                    data.put("carrierBankNum", "--");
                }else {
                    data.put("carrierBankNum", hyCarrier.getBankNum());
                }
            }

            //遍历map集合，对应的填进去，本人测试过，如果没有与黑底的字段匹配的，那么那个部分数据填充就是空
            for (String key : data.keySet()) {
                form.setField(key, String.valueOf(data.get(key)));
            }
            ps.setFormFlattening(true);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(e.toString());
        } finally {
            try {
                ps.close();
                reader.close();
                os.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return Result.OK(outputName2);
    }

    //税务授权协议签署
    public Result addSignetForTax(String orderId,HyDriver driver, String signetPath) throws IOException {

        HyOrder order = hyOrderService.getById(orderId);

        if (order == null) {
            return Result.error("货源信息异常!");
        }
        HyCustomer customer = hyCustomerService.getById(order.getCustomerId());
        if (customer == null) {
            return Result.error("未查询到货主信息!");
        }
        HyCustomerCompany customerCompany = hyCustomerCompanyService.getByCustomerId(order.getCustomerId());
        if (customerCompany == null) {
            return Result.error("货主未绑定分公司");
        }
        HyCompany company = hyCompanyService.getById(customerCompany.getCompanyId());
        if (company == null) {
            return Result.error("分公司信息不存在");
        }
        if (StringUtils.isEmpty(company.getElectronicSeal())) {
            return Result.error("请配置分公司电子公章");
        }

        String pathSubfix = uploadpath + File.separator;
        //模板路径
        String shippingTemplatePath = pathSubfix + hySettingService.getSettingValueByTag("driver_tax_template");

        //输出路径
        String outputName2 = SAVE_CONTRACT_ADDR + SHIPPING_NAME_SUBFIX
                + DateUtils.getDate("yyyyMMddHHmmss") + "_" + System.currentTimeMillis() + PDF_SUFFIX;
        String outputName = pathSubfix + outputName2;

        File fileDir = new File(pathSubfix + SAVE_CONTRACT_ADDR);
        if (!fileDir.exists()) {
            fileDir.mkdirs();//创建目录
        }

        //乙方签名图片地址
        String yf_img = pathSubfix + signetPath;
        byte[] yfbytes = null;

        //甲方电子公章图片地址
        String jf_img = pathSubfix + company.getElectronicSeal();
        byte[] bytes = null;

        //图片的输入流
        FileInputStream fileInputStream = new FileInputStream(jf_img);
        bytes = new byte[fileInputStream.available()];
        fileInputStream.read(bytes);

        OutputStream os = null;
        PdfStamper ps = null;
        PdfReader reader = null;

        try {

            FileInputStream fileInputStream3 = new FileInputStream(shippingTemplatePath);

            //图片的输入流2
            FileInputStream fileInputStream2 = new FileInputStream(yf_img);
            yfbytes = new byte[fileInputStream2.available()];
            fileInputStream2.read(yfbytes);
            //图片转码
            BASE64Encoder encoder = new BASE64Encoder();
            os = new FileOutputStream(new File(outputName));
            //读取pdf表单
            reader = new PdfReader(fileInputStream3);
            //根据表单生成一个新的pdf文件
            ps = new PdfStamper(reader, os);
            //获取pdf表单
            AcroFields form = ps.getAcroFields();
            //给表单中添加中文字体
            BaseFont bf = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
            form.addSubstitutionFont(bf);
            Map<String, Object> data = new HashMap<String, Object>();

            //乙方名称
            data.put("siji", driver.getDriverName());
            //住址
            data.put("address", driver.getAddress());
            data.put("telephone", driver.getTelephone());

            //甲方合同章
            data.put("jf_img", encoder.encode(bytes));

            //乙方签字章
            data.put("siji_img", encoder.encode(yfbytes));
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年MM月dd日");
            data.put("date", simpleDateFormat.format(new Date()));

            //遍历map集合，对应的填进去，本人测试过，如果没有与黑底的字段匹配的，那么那个部分数据填充就是空
            for (String key : data.keySet()) {
                form.setField(key, String.valueOf(data.get(key)));
            }
            ps.setFormFlattening(true);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(e.toString());
        } finally {
            try {
                ps.close();
                reader.close();
                os.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return Result.OK(outputName2);
    }


    //税务授权协议签署 -泰新需求  使用时需要在系统设置项里添加kaiyun_template pdf文件
    public Result kaiyundaikai(String orderId,HyDriver driver, String signetPath) throws IOException {

        HyOrder order = hyOrderService.getById(orderId);

        if (order == null) {
            return Result.error("货源信息异常!");
        }
        HyCustomer customer = hyCustomerService.getById(order.getCustomerId());
        if (customer == null) {
            return Result.error("未查询到货主信息!");
        }
        HyCustomerCompany customerCompany = hyCustomerCompanyService.getByCustomerId(order.getCustomerId());
        if (customerCompany == null) {
            return Result.error("货主未绑定分公司");
        }
        HyCompany company = hyCompanyService.getById(customerCompany.getCompanyId());
        if (company == null) {
            return Result.error("分公司信息不存在");
        }
        if (StringUtils.isEmpty(company.getElectronicSeal())) {
            return Result.error("请配置分公司电子公章");
        }

        String pathSubfix = uploadpath + File.separator;
        log.info("pathSubfix路径为"+pathSubfix);
        //模板路径
        String shippingTemplatePath = pathSubfix + hySettingService.getSettingValueByTag("kaiyun_template");
        log.info("shippingTemplatePath"+pathSubfix);
        //输出路径
        String outputName2 = SAVE_CONTRACT_ADDR + "开运代开_" + DateUtils.getDate("yyyyMMddHHmmss") + PDF_SUFFIX;
        String outputName = pathSubfix + outputName2;
        log.info("outputName"+outputName);

        File fileDir = new File(pathSubfix + SAVE_CONTRACT_ADDR);
        if (!fileDir.exists()) {
            fileDir.mkdirs();//创建目录
        }

        if(StringUtils.isEmpty(signetPath)){
            signetPath=driver.getDriverAutograph();
        }
        //乙方签名图片地址
        String yf_img = pathSubfix + signetPath;
        byte[] yfbytes = null;

        //甲方电子公章图片地址
        String jf_img = pathSubfix + company.getElectronicSeal();
        byte[] bytes = null;

        //图片的输入流
        FileInputStream fileInputStream = new FileInputStream(jf_img);
        bytes = new byte[fileInputStream.available()];
        fileInputStream.read(bytes);

        OutputStream os = null;
        PdfStamper ps = null;
        PdfReader reader = null;

        try {

            FileInputStream fileInputStream3 = new FileInputStream(shippingTemplatePath);

            //图片的输入流2
            FileInputStream fileInputStream2 = new FileInputStream(yf_img);
            yfbytes = new byte[fileInputStream2.available()];
            fileInputStream2.read(yfbytes);
            //图片转码
            BASE64Encoder encoder = new BASE64Encoder();
            os = new FileOutputStream(new File(outputName));
            //读取pdf表单
            reader = new PdfReader(fileInputStream3);
            //根据表单生成一个新的pdf文件
            ps = new PdfStamper(reader, os);
            //获取pdf表单
            AcroFields form = ps.getAcroFields();
            //给表单中添加中文字体
            BaseFont bf = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
            form.addSubstitutionFont(bf);
            Map<String, Object> data = new HashMap<String, Object>();

            //乙方名称
            data.put("name", driver.getDriverName());
            //住址
            data.put("address", driver.getAddress());
            data.put("idcard", driver.getIdcard());

            //甲方合同章
//            data.put("jf_img", encoder.encode(bytes));

            //乙方签字章
            data.put("siji_img", encoder.encode(yfbytes));
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年MM月dd日");
            data.put("date", simpleDateFormat.format(new Date()));
            Calendar cal = Calendar.getInstance();
            cal.add(Calendar.YEAR, 1);
            data.put("date2", simpleDateFormat.format(cal.getTime()));

            //遍历map集合，对应的填进去，本人测试过，如果没有与黑底的字段匹配的，那么那个部分数据填充就是空
            for (String key : data.keySet()) {
                form.setField(key, String.valueOf(data.get(key)));
            }
            ps.setFormFlattening(true);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(e.toString());
        } finally {
            try {
                ps.close();
                reader.close();
                os.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return Result.OK(outputName2);
    }
    //税务授权协议签署 -泰新需求  使用时需要在系统设置项里添加xinluyun_template pdf文件
    public Result xinluyundaikai(String orderId,HyDriver driver, String signetPath) throws IOException {

        HyOrder order = hyOrderService.getById(orderId);

        if (order == null) {
            return Result.error("货源信息异常!");
        }
        HyCustomer customer = hyCustomerService.getById(order.getCustomerId());
        if (customer == null) {
            return Result.error("未查询到货主信息!");
        }
        HyCustomerCompany customerCompany = hyCustomerCompanyService.getByCustomerId(order.getCustomerId());
        if (customerCompany == null) {
            return Result.error("货主未绑定分公司");
        }
        HyCompany company = hyCompanyService.getById(customerCompany.getCompanyId());
        if (company == null) {
            return Result.error("分公司信息不存在");
        }
        if (StringUtils.isEmpty(company.getElectronicSeal())) {
            return Result.error("请配置分公司电子公章");
        }

        String pathSubfix = uploadpath + File.separator;
        log.info("pathSubfix路径为"+pathSubfix);
        //模板路径
        String shippingTemplatePath = pathSubfix + hySettingService.getSettingValueByTag("xinluyun_template");
        log.info("shippingTemplatePath"+pathSubfix);
        //输出路径
        String outputName2 = SAVE_CONTRACT_ADDR + "新陆运代开_" + DateUtils.getDate("yyyyMMddHHmmss") + PDF_SUFFIX;
        String outputName = pathSubfix + outputName2;
        log.info("outputName"+outputName);

        File fileDir = new File(pathSubfix + SAVE_CONTRACT_ADDR);
        if (!fileDir.exists()) {
            fileDir.mkdirs();//创建目录
        }

        if(StringUtils.isEmpty(signetPath)){
            signetPath=driver.getDriverAutograph();
        }
        //甲方签名图片地址
        String jf_img = pathSubfix + signetPath;
        byte[] jfbytes = null;

        //丙方电子公章图片地址
        String bf_img = pathSubfix + company.getElectronicSeal();
        byte[] bytes = null;

        //图片的输入流
        FileInputStream fileInputStream = new FileInputStream(bf_img);
        bytes = new byte[fileInputStream.available()];
        fileInputStream.read(bytes);

        OutputStream os = null;
        PdfStamper ps = null;
        PdfReader reader = null;

        try {

            FileInputStream fileInputStream3 = new FileInputStream(shippingTemplatePath);
            log.info("开始抠图填充数据");
            //图片的输入流2
            FileInputStream fileInputStream2 = new FileInputStream(jf_img);
            jfbytes = new byte[fileInputStream2.available()];
            fileInputStream2.read(jfbytes);
            //图片转码
            BASE64Encoder encoder = new BASE64Encoder();
            os = new FileOutputStream(new File(outputName));
            //读取pdf表单
            reader = new PdfReader(fileInputStream3);
            //根据表单生成一个新的pdf文件
            ps = new PdfStamper(reader, os);
            //获取pdf表单
            AcroFields form = ps.getAcroFields();
            //给表单中添加中文字体
            BaseFont bf = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
            form.addSubstitutionFont(bf);
            Map<String, Object> data = new HashMap<String, Object>();

            /*//乙方名称
            data.put("name", driver.getDriverName());
            //住址
            data.put("address", driver.getAddress());
            data.put("idcard", driver.getIdcard());

            //甲方合同章
//            data.put("jf_img", encoder.encode(bytes));

            //乙方签字章
            data.put("siji_img", encoder.encode(yfbytes));
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年MM月dd日");
            data.put("date", simpleDateFormat.format(new Date()));
            Calendar cal = Calendar.getInstance();
            cal.add(Calendar.YEAR, 1);
            data.put("date2", simpleDateFormat.format(cal.getTime()));*/
            //甲方名称
            data.put("jiafangname", driver.getDriverName());
            data.put("idcard", driver.getIdcard());

            //丙方
            data.put("bingfangname",company.getCompanyName());
            data.put("creditCode",company.getCreditCode());
            data.put("file_2",company.getCompanyName());

            //签章
            data.put("siji_img", encoder.encode(jfbytes));//甲方
            data.put("bf_img",encoder.encode(bytes));//丙方签章
            /*SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年MM月dd日");
            Calendar cal = Calendar.getInstance();
            cal.add(Calendar.YEAR, 1);
            data.put("date1", simpleDateFormat.format(cal.getTime()));
            cal.add(Calendar.MONTH, 2);
            data.put("date2", simpleDateFormat.format(cal.getTime())+1);
            cal.add(Calendar.DAY_OF_MONTH, 5);
            data.put("date3",simpleDateFormat.format(cal.getTime()));*/
            LocalDateTime now = LocalDateTime.now();
            int year = now.getYear();
            int month = now.getMonthValue();
            int day = now.getDayOfMonth();
            data.put("date1", year);
            data.put("date2", month);
            data.put("date3",day);
            //遍历map集合，对应的填进去，本人测试过，如果没有与黑底的字段匹配的，那么那个部分数据填充就是空
            for (String key : data.keySet()) {
                form.setField(key, String.valueOf(data.get(key)));
            }
            ps.setFormFlattening(true);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(e.toString());
        } finally {
            try {
                ps.close();
                reader.close();
                os.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return Result.OK(outputName2);
    }



    //司机签署挂靠协议 使用时需要在系统设置项里添加driver_hang_template pdf文件 中惠需求
    public Result driverAffiliationForZhonghui(HyDriver driver, String signetPath) throws IOException {

//        HyOrder order = hyOrderService.getById(orderId);
//
//        if (order == null) {
//            return Result.error("货源信息异常!");
//        }
//        HyCustomer customer = hyCustomerService.getById(order.getCustomerId());
//        if (customer == null) {
//            return Result.error("未查询到货主信息!");
//        }
//        HyCustomerCompany customerCompany = hyCustomerCompanyService.getByCustomerId(order.getCustomerId());
//        if (customerCompany == null) {
//            return Result.error("货主未绑定分公司");
//        }

        List<HyCompany> companyList = hyCompanyService.list();
        if (CollUtil.isEmpty(companyList)) {
            return Result.error("公司信息不存在");
        }

        HyCompany company = companyList.get(0);
        if (StringUtils.isEmpty(company.getElectronicSeal())) {
            return Result.error("请配置分公司电子公章");
        }

        String pathSubfix = uploadpath + File.separator;
        //模板路径
        String shippingTemplatePath = pathSubfix + hySettingService.getSettingValueByTag("driver_hang_template");

        //输出路径
        String outputName2 = SAVE_CONTRACT_ADDR + SHIPPING_NAME_SUBFIX + DateUtils.getDate("yyyyMMddHHmmss") + PDF_SUFFIX;
        String outputName = pathSubfix + outputName2;

        File fileDir = new File(pathSubfix + SAVE_CONTRACT_ADDR);
        if (!fileDir.exists()) {
            fileDir.mkdirs();//创建目录
        }

        //乙方签名图片地址
        String yf_img = pathSubfix + signetPath;
        byte[] yfbytes = null;

        //甲方电子公章图片地址
        String jf_img = pathSubfix + company.getElectronicSeal();
        byte[] bytes = null;

        //图片的输入流
        FileInputStream fileInputStream = new FileInputStream(jf_img);
        bytes = new byte[fileInputStream.available()];
        fileInputStream.read(bytes);

        OutputStream os = null;
        PdfStamper ps = null;
        PdfReader reader = null;

        try {

            FileInputStream fileInputStream3 = new FileInputStream(shippingTemplatePath);

            //图片的输入流2
            FileInputStream fileInputStream2 = new FileInputStream(yf_img);
            yfbytes = new byte[fileInputStream2.available()];
            fileInputStream2.read(yfbytes);
            //图片转码
            BASE64Encoder encoder = new BASE64Encoder();
            os = new FileOutputStream(new File(outputName));
            //读取pdf表单
            reader = new PdfReader(fileInputStream3);
            //根据表单生成一个新的pdf文件
            ps = new PdfStamper(reader, os);
            //获取pdf表单
            AcroFields form = ps.getAcroFields();
            //给表单中添加中文字体
            BaseFont bf = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
            form.addSubstitutionFont(bf);
            Map<String, Object> data = new HashMap<String, Object>();

            //乙方名称
            data.put("siji", driver.getDriverName());

            //甲方合同章
            data.put("jf_img", encoder.encode(bytes));

            //乙方签字章
            data.put("siji_img", encoder.encode(yfbytes));
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年MM月dd日");
            data.put("date", simpleDateFormat.format(new Date()));

            //遍历map集合，对应的填进去，本人测试过，如果没有与黑底的字段匹配的，那么那个部分数据填充就是空
            for (String key : data.keySet()) {
                form.setField(key, String.valueOf(data.get(key)));
            }
            ps.setFormFlattening(true);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(e.toString());
        } finally {
            try {
                ps.close();
                reader.close();
                os.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return Result.OK(outputName2);
    }


    public static String digitCapital(double n) {
        String fraction[] = {"角", "分"};
        String digit[] = {"零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖"};
        String unit[][] = {{"元", "万", "亿"}, {"", "拾", "佰", "仟"}};

        String head = n < 0 ? "负" : "";
        // 如果是负数取绝对值
        n = Math.abs(n);
        String s = "";
        BigDecimal bigDecimal = new BigDecimal(Double.valueOf(n).toString());
        String nStr = bigDecimal.toString();
        // 小数部分
        String[] split = nStr.split("\\.");
        if (split.length > 1) {
            // 小数点为特殊符号，在分割时需进行转义
            String decimalStr = split[1];
            if (decimalStr.length() > 2) {
                decimalStr = decimalStr.substring(0, 2);
            }
            // 将小数部分转换为整数
            Integer integer = Integer.valueOf(decimalStr);
            String p = "";
            for (int i = 0; i < decimalStr.length() && i < fraction.length; i++) {
                p = digit[integer % 10] + fraction[decimalStr.length() - i - 1] + p;
                integer = integer / 10;
            }
            s = p.replaceAll("(零.)+", "") + s;
        }
        if (s.length() < 1) {
            s = "整";
        }
        int integerPart = (int)Math.floor(n);
        // 整数部分
        for (int i = 0; i < unit[0].length && integerPart > 0; i++) {
            String p = "";
            for (int j = 0; j < unit[1].length && n > 0; j++) {
                p = digit[integerPart % 10] + unit[1][j] + p;
                integerPart = integerPart / 10;
            }
            s = p.replaceAll("(零.)*零$", "").replaceAll("^$", "零") + unit[0][i] + s;
        }
        return head + s.replaceAll("(零.)*零元", "元").replaceFirst("(零.)+", "").replaceAll("(零.)+", "零").replaceAll("^整$", "零元整");
    }




    //Service调用
    public Result pdfUtilServiceGet(String shippingId) {

        HyShippingNote hyShippingNote = hyShippingNoteService.getById(shippingId);
        if (hyShippingNote == null) {
            return Result.error("运单信息异常!");
        }
        HyOrder orderObj = hyOrderService.getById(hyShippingNote.getOrderId());
        if (orderObj == null) {
            return Result.error("货源信息异常!");
        }
        HyCustomerCompany customerCompany = hyCustomerCompanyService.getByCustomerId(hyShippingNote.getCustomerId());
        if (customerCompany == null) {
            return Result.error("货主未绑定分公司");
        }
        HyCompany company = hyCompanyService.getById(customerCompany.getCompanyId());
        if (company == null) {
            return Result.error("分公司信息不存在");
        }
        if (StringUtils.isEmpty(company.getElectronicSeal())) {
            return Result.error("请配置分公司电子公章");
        }
        HyDriver driver = hyDriverService.getById(hyShippingNote.getDriverId());

        if (StringUtils.isEmpty(driver.getDriverAutograph())) {
            return Result.error("司机签名图片不能为空");
        }

       /* if ("0".equals(hyShippingNote.getContractOr())) {


            Result result = generatePDF.pdfUtil(joOrder,hyShippingNote, driver);
            if(result.isSuccess()){
                hyShippingNote.setShippingContract(result.getResult().toString());
                String contractNum = CodeUtil.createContractNum();
                hyShippingNote.setContractNum(contractNum);
                hyShippingNote.setContractNum2(contractNum);
                hyShippingNote.setContractType("承运人电子合同");
                hyShippingNote.setContractStatus("1");
                hyShippingNote.setContractOr("0");
                hyShippingNoteService.updateById(hyShippingNote);
            } else {
                return result;
            }
        }*/
        JSONObject order = dictUtil.parseObjectDict(orderObj);

        if (order == null) {
            return Result.error("货源信息异常!");
        }
        HyCustomer customer = hyCustomerService.getById(order.get("customerId").toString());
        if (customer == null) {
            return Result.error("未查询到货主信息!");
        }
        if (StringUtils.isEmpty(company.getElectronicSeal())) {
            return Result.error("请配置分公司电子公章");
        }
        if (StringUtils.isEmpty(driver.getDriverAutograph())) {
            return Result.error("司机签名图片不存在");
        }

        String pathSubfix = uploadpath + File.separator;
        //模板路径
        String shippingTemplatePath = pathSubfix + hySettingService.getSettingValueByTag("driver_shipping_template");

        //输出路径
        String outputName2 = SAVE_CONTRACT_ADDR + SHIPPING_NAME_SUBFIX + DateUtils.getDate("yyyyMMddHHmmss") + PDF_SUFFIX;
        String outputName = pathSubfix + outputName2;

        File fileDir = new File(pathSubfix + SAVE_CONTRACT_ADDR);
        if (!fileDir.exists()) {
            fileDir.mkdirs();//创建目录
        }
        //甲方电子公章图片地址
        String jf_img = pathSubfix + company.getElectronicSeal();
        byte[] bytes = null;

        //乙方签名图片地址
        String yf_img = pathSubfix + driver.getDriverAutograph();
        byte[] yfbytes = null;

        OutputStream os = null;
        PdfStamper ps = null;
        PdfReader reader = null;

        log.info("开始生成PDF合同 {}, {}, {}, {}, {}", driver.getDriverName(), outputName2, pathSubfix + SAVE_CONTRACT_ADDR, jf_img, yf_img);
        try {
            FileInputStream fileInputStream3 = new FileInputStream(shippingTemplatePath);
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年MM月dd日");

            //图片的输入流
            FileInputStream fileInputStream = new FileInputStream(jf_img);
            bytes = new byte[fileInputStream.available()];
            fileInputStream.read(bytes);

            //图片的输入流2
            FileInputStream fileInputStream2 = new FileInputStream(yf_img);
            yfbytes = new byte[fileInputStream2.available()];
            fileInputStream2.read(yfbytes);

            //图片转码
            BASE64Encoder encoder = new BASE64Encoder();
            os = new FileOutputStream(new File(outputName));
            //读取pdf表单
            reader = new PdfReader(fileInputStream3);
            //根据表单生成一个新的pdf文件
            ps = new PdfStamper(reader, os);
            //获取pdf表单
            AcroFields form = ps.getAcroFields();
            //给表单中添加中文字体
            BaseFont bf = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
            form.addSubstitutionFont(bf);
            Map<String, Object> data = new HashMap<String, Object>();

            //甲方名称
            data.put("jf", company.getCompanyName());
            //乙方名称
            data.put("yf", driver.getDriverName());

            //甲方合同章
            data.put("jf_img", encoder.encode(bytes));
            //乙方签字章
            data.put("yf_img", encoder.encode(yfbytes));
            //货源号
            data.put("orderNum", order.getString("orderNum"));
            //货物名称
            data.put("descriptionOfGoods", order.getString("descriptionOfGoods"));

            //货物总重量
            if (order.getString("totalGoodsWeight") == null) {
                data.put("totalGoodsWeight", "--");
            } else {
                data.put("totalGoodsWeight", order.getString("totalGoodsWeight"));

            }
            //运费计算方式
            data.put("shippingType", order.getString("shippingType_dictText"));

            //亏损货物单价
            data.put("lossGoodsUnitPrice", order.getString("lossGoodsUnitPrice"));
            //免赔方式
            data.put("lossType", order.getString("lossType_dictText"));
            //发货地址
            data.put("sendAddressName", order.getString("sendAddressName"));
            //发货人
            data.put("sendContactName", order.getString("sendContactName"));
            //发货联系人电话
            data.put("sendContactTel", order.getString("sendContactTel"));

            //FIXME 这里有BUG：发货和收货时间要格式化数据，现在格式是这样的
            // -> Wed Jul 05 08:15:04 CST 2023 ,所以toDatetime会异常
//            log.info("发货时间， {}", order.getString("sendDate"));
//            if (order.getString("sendDate") != null) {
//                //发货时间
//                Date orderSendDate = DateUtils.stringToDateTime(order.getString("sendDate"));
//                data.put("sendDate", simpleDateFormat.format(orderSendDate));
//            } else {
//                //发货时间
//                data.put("sendDate", "--");
//            }

            //收货地址
            data.put("receiveAddressName", order.getString("receiveAddressName"));
            //收货人
            data.put("receiveContactName", order.getString("receiveContactName"));
            //收货联系人电话
            data.put("receiveContactTel", order.getString("receiveContactTel"));
//            if (order.getString("receiveDate") != null) {
//                //收货时间
//                Date orderReceiveDate = DateUtils.stringToDateTime(order.getString("receiveDate"));
//                data.put("receiveDate", simpleDateFormat.format(orderReceiveDate));
//            } else {
//                //收货时间
//                data.put("receivedDate", "--");
//            }

            //货物单价(系统暂无)
            data.put("goodsUnitPrice", "--");

            if (hyShippingNote != null) {
                //装货时间
                if (ObjectUtil.isNotEmpty(hyShippingNote.getStatusDtLoading())) {
                    data.put("statusDtLoading", simpleDateFormat.format(hyShippingNote.getStatusDtLoading()));
                    //签订日期
                    data.put("date", simpleDateFormat.format(hyShippingNote.getStatusDtLoading()));
                }
                //收货时间
                if (ObjectUtil.isNotEmpty(hyShippingNote.getStatusDtUnloading())) {
                    data.put("statusDtUnloading", simpleDateFormat.format(hyShippingNote.getStatusDtUnloading()));
                }

                //运量
                if (ObjectUtil.isNotEmpty(hyShippingNote.getGoodsWeightLoading())) {
                    data.put("goodsWeightLoading", hyShippingNote.getGoodsWeightLoading());
                }
                //运费单价
                data.put("shippingUnitPrice",hyShippingNote.getShippingUnitPrice());

            } else {
                //装货时间
                data.put("statusDtLoading", simpleDateFormat.format(new Date()));
                //运量
                data.put("goodsWeightLoading", "--");
                //签订日期
                data.put("date", simpleDateFormat.format(new Date()));

                //运费单价
                data.put("shippingUnitPrice", order.getString("shippingUnitPrice"));
            }

            //司机信息
            //司机姓名
            data.put("driverName", driver.getDriverName());
            //司机电话
            data.put("telephone", driver.getTelephone());
            List<HyDriverBank> driverBanks = driverBankService.getByDriverId(driver.getId());
            if(driverBanks.size()==0){
                //司机开户行
                data.put("bankType", "--");
                //司机银行卡
                data.put("bankNum", "--");
            }else{
                //司机开户行
                data.put("bankType", driverBanks.get(0).getBankType());
                //司机银行卡
                data.put("bankNum", driverBanks.get(0).getBankNum());
            }
            //大写金额
            String DXshippingUnitPrice = digitCapital(Double.parseDouble(order.getString("shippingUnitPrice")));
            data.put("DXshippingUnitPrice", DXshippingUnitPrice);


            //遍历map集合，对应的填进去，本人测试过，如果没有与黑底的字段匹配的，那么那个部分数据填充就是空
            for (String key : data.keySet()) {
                form.setField(key, String.valueOf(data.get(key)));
            }
            ps.setFormFlattening(true);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(e.toString());
        } finally {
            try {
                ps.close();
                reader.close();
                os.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return Result.OK(outputName2);
    }


}
